<?php
    class product_Ajax extends Ajax
    {
        public function addComent()
        {
            $data ='';
            core::checkSession();
            $oDatabase = new database();
            $time = time();
            $aData = array();
            $this->addNofication();
            if(isset($_POST['id_reply']))
            {
                $aData = array(
                    'masp_id' =>$_POST['masp'],
                    'user' =>$_POST['user'],
                    'noidung' => $_POST['comment'],
                    'thoigian' =>$time,
                    'reply_id'=>$_POST['id_reply']
                );
            }
            else
            {
                $aData = array(
                    'masp_id' =>$_POST['masp'],
                    'user' =>$_POST['user'],
                    'noidung' => $_POST['comment'],
                    'thoigian' =>$time,
                );
            }
            $result = $oDatabase->add('binhluan',$aData); 
            $data .= $result .';' . date('H:i Y-m-d' ,$time);
            echo $data;
        }
        public function addNofication()
        {
            core::checkSession();
            $oDatabase = new database();
            $arrayUser =array();
            // Add nofication when comment
            $queryFollow ='PREFIX foaf: <http://xmlns.com/foaf/0.1/>
            PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
            PREFIX dc: <http://purl.org/dc/elements/1.1/>
            PREFIX bus: <'.URL::getLink('id/bussiness#').'>

            SELECT * 
            WHERE
            {
            ?uri rdf:type foaf:Person.
            ?uri foaf:givenName ?name.
            OPTIONAL {?uri bus:followProduct ?followProduct.}
            FILTER(?followProduct="'.URL::getLink('product/id/'.$_POST['masp']).'" )
            }';
            $aUserFollow = $oDatabase->loadQuery($queryFollow);   
            $listUserFollow=$aUserFollow['result']['rows'];
            if(count($listUserFollow))
            {
                foreach($listUserFollow as $user)
                {
                    if($user['name'] != $_SESSION['username'])
                    {
                        array_push($arrayUser,$user['name']);
                    }
                }
            }
            $queryUserComment = 'SELECT DISTINCT user FROM binhluan WHERE masp_id = "'.$_POST['masp'].'"';
            $aUserComment = $oDatabase->getListObject($queryUserComment);
            if(count($aUserComment))
            {
                foreach($aUserComment as $user)
                {
                    if(!in_array($user->user,$arrayUser) && $user->user != $_SESSION['username'])
                    {
                        array_push($arrayUser,$user->user);
                    }
                }
            }
            if(!in_array($_POST['givename'],$arrayUser)&& $_POST['givename']!=$_SESSION['username'])
            {
                array_push($arrayUser,$_POST['givename']);
            }
            $product = $_POST['nameProduct'];
            $name =$product;
            if(strlen($product) >30)
            {
                $name= substr ($product,0,19).'...';
            }
            $content = 'đã đăng bình luận về sản phẩm '.$name.' . ';
            if(count($arrayUser))
            {
                foreach($arrayUser as $user)
                {
                    $aData = array(
                        'user_send' => $_SESSION['username'],
                        'content' => $content ,
                        'user_to' =>$user,
                        'type' => 2,// Type 2 : add comment  send owner product
                        'status' => 1,
                        'time' =>time(),
                        'avata' => $_SESSION['avatar'],
                        'product' => $_POST['masp'],
                        'poup' => 1,
                    );
                    $result = $oDatabase->add('nofication',$aData); 
                }
            }
            //
        }
        public function updateLike()
        {
            core::checkSession();
            $oDatabase = new database();
            $user = $_POST['user'];
            $comment_id = $_POST['comment_id'];
            $like = $_POST['like'];
            $do = $_POST['skill'];
            $aCondition = array(
                'comment_id = '.$comment_id => '',
            );
            $aData = array(
                'like_comment' => $like,  
            );
            $result = $oDatabase->update('binhluan',$aData, $aCondition);
            if($do == 1)
            {
                $aData = array(
                    'user' =>$user,
                    'comment_id' =>$comment_id,
                );
                $result = $oDatabase->add('comment_like',$aData); 
                $user_comment = $_POST['user_comment'];
                if($user_comment!=$user)
                {
                    $content = 'đã thích bình luận của bạn . ';
                    $aData = array(
                        'user_send' => $user,
                        'content' => $content ,
                        'user_to' =>$user_comment,
                        'type' => 3,// Type 3 : like comment
                        'status' => 1,
                        'time' =>time(),
                        'avata' => $_SESSION['avatar'],
                        'product' => $_POST['masp'],
                        'poup' =>1,
                    );
                    $result = $oDatabase->add('nofication',$aData); 
                }
            }
            else
            {
                $aCondition = array(
                    "user ='".$user."'" =>'AND',
                    "comment_id =".$comment_id =>''
                );
                $result = $oDatabase->delete('comment_like', $aCondition);
            }
            echo $oDatabase->sSql;

        }
        public function loadReply()
        {
            core::checkSession();
            $oDatabase = new database();
            $query ='Select avatar,comment_id,masp_id,user,noidung,thoigian,like_comment,reply_id from user,binhluan where user.user_id = binhluan.user and reply_id="'.$_POST['commnet_id'].'" ORDER BY comment_id ASC ';
            $aComment = $oDatabase->getListObject($query);
            $data ='';
            if(count($aComment))
            {
                $like ='Thích';
                $username ='';
                if(isset($_SESSION['username']))
                {
                    $username = $_SESSION['username'];
                }
                foreach($aComment as $coment)
                {
                    $like = 'Thích';
                    if($username !='')
                    {
                        $query = 'SELECT * FROM comment_like WHERE user ="'.$username.'" AND comment_id ='.$coment->comment_id;
                        $aLike = $oDatabase->getListObject($query);
                        if(count($aLike))
                        {
                            $like ='Không thích';
                        }
                    }
                    $data.=' <div class="li_comment_reply">' ;
                    $data.='<div style="margin-bottom: 10px;">';
                    $data.='  <div class="image_content" style="float: left; width: 10%;">';
                    $data.='<img style=" max-height: 60px; max-width: 60px;" src="'.URL::getLink('upload/'.$coment->avatar).'"></div>';
                    $data.='<div class="reply_content" style="float:left;padding-left: 20px; width: 85%;">';
                    $data.=' <div class="arer_comment">';
                    $data.='<label hidden="" class="id_comment_reply">'.$coment->comment_id.'</label>';
                    $data.='<label class="user_comment" style="color: #DF1B23; font-weight: bold;">'.$coment->user.'</label>';
                    $data.='<label class="time_publish" style=" float: right; font-size: 12px; color: #A6A6A6; ">Lúc: '.date('H:i Y-m-d' ,$coment->thoigian).'</label><br>';
                    $data.='<label>'.$coment->noidung.'</label><br>';
                    $data.='<label><a class="like_comment_reply" style="cursor: pointer;">'.$like.'</a> <img style="" src="'.URL::getLink('image/like.png').'"><label class="count_like_reply" style="margin-left: 2px;">'.$coment->like_comment.'</label></label><br>';
                    $data.='</div></div>';
                    $data.='</div><div class="add_reply" style="clear: both;"></div></div>';
                }
            }
            echo $data;
        }
        public function loadMore()
        {
            $like ='Thích';
            $username ='';
            $respone =0;
            if(isset($_SESSION['username']))
            {
                $username = $_SESSION['username'];
            }
            $domain =5;
            $oDatabase = new database();
            $query ='select * from binhluan where masp_id="'.$_POST['masp'].'" ORDER BY comment_id DESC LIMIT '.$_POST['limit'].','.$domain;
            $aListProduct = $oDatabase->getListObject($query);
            $coment ='';
            if(count($aListProduct))
            {
                foreach($aListProduct as $coment)
                {
                    $like = 'Thích';
                    $respone =0;
                    $query = 'Select * from comment_like where user ="'.$username.'" and comment_id ='.$coment->comment_id;
                    $aLike = $oDatabase->getListObject($query);
                    if(count($aLike))
                    {
                        $like ='Không thích';
                    }
                    $queryReply =' Select * from binhluan where reply_id = '.$coment->comment_id;
                    $aReply = $oDatabase->getListObject($queryReply);
                    {
                        if(count($aReply))
                        {
                            $respone = count($aReply);
                        }
                    }
                    $html ='';
                    $html.=' <div class="li_comment">';
                    $html.='<div style="margin-bottom: 20px;">';
                    $html.='  <div style="float: left; width: 10%;">';
                    $html.='<img style=" height: 60px; width: 60px;" src="'.$coment->img.'">';
                    $html.='</div>';
                    $html.='<div style="float: left;padding-left: 10px; width: 85%;">';
                    $html.=' <div class="arer_comment"><label hidden="" class="id_comment">'.$coment->comment_id.'</label>';
                    $html.='<label style="color: #DF1B23; font-weight: bold;">'.$coment->user.'</label>';
                    $html.='<label style=" margin-left: 250px; font-size: 12px; color: #A6A6A6; ">Lúc:'.$coment->thoigian.'</label><br>';
                    $html.='<label style="font: 200 13px/1.5 Georgia, Times New Roman, serif;">'.$coment->noidung.'</label><br>';
                    $html.='<label style="font: 200 11px/1.5 Georgia, Times New Roman, serif; color: #3581e0;"><a style="cursor: pointer;" class="reply_coment">Trả lời</a>
                    $html.=<a class="like_comment" style="cursor: pointer;padding-left: 10px;">'.$like .'</a>'; 
                    $html.='<img style="" src="'.URL::getLink('image/like.png').'">';
                    $html.='<label class="count_like" style="margin-left: 2px;">'.$coment->like_comment.'</label> <a class="respone_comment"  style="cursor: pointer;">Phản hồi('. $respone.')</a></label><br>';
                    $html.='<div class="reply_addAfter" hidden="true"></div>';
                    $html.='</div>';
                    $html.=' </div>';
                    $html.='</div><div class="add_reply" style="clear: both;"></div>';
                    $html.=' </div>';
                    $coment.=$html;
                }
                $querycount ='select * from binhluan where masp_id="'.$_POST['masp'].'"';
                $aList = $oDatabase->getListObject($querycount);
                $count = (int)$_POST['limit'] +$domain;
                if(count($aList)>$count)
                {
                    $coment.='*&*true';
                }
                else
                {
                    $coment.='*&*false';
                }
            }
            echo $coment;
        }

        public function updateProduct()
        {
            $oDatabase = new database();
            $nameproduct = $_POST['nameproduct'];
            $price = $_POST['price'];
            $manufacter = $_POST['manufacter'];
            $describe = $_POST['describe'];
            $category = $_POST['category'];
            core::checkSession();
            $product_id = $_POST['idproduct'];
            $sType = 'product';
            $aNameSpace = array(
                'rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
                'bus' => URL::getLink('id/bussiness#'),
            );
            $uri = URL::getLink($sType."/id/".$product_id); 
            $data = array(
                $uri => array(
                    "rdf:type" => array( 
                        array( "value" => URL::getLink("id/bussiness#product"), 
                            "type" => "uri" ) 
                    ) ,
                    "bus:name" => array(
                        array( "value" => $_POST['nameproduct'], 
                            "type" => "literal")
                    ),
                    "bus:price" => array(
                        array( "value" => $_POST['price'], 
                            "type" => "literal")
                    ),
                    "bus:description" => array(
                        array( "value" => $_POST['describe'], 
                            "type" => "literal")
                    ),
                    "bus:price" => array(
                        array( "value" => $_POST['price'], 
                            "type" => "literal")
                    ),
                    "bus:image" => array(
                        array( "value" => $_POST['image'], 
                            "type" => "literal")
                    ),
                    "bus:location" => array(
                        array( "value" => $_POST['location'], 
                            "type" => "literal")
                    ),
                    "bus:hasCategory" => array(
                        array( "value" => $_POST['subcatalog'], 
                            "type" => "uri")
                    ),
                    "bus:hasManufacturer" => array(
                        array( "value" => $_POST['manufacter'], 
                            "type" => "uri")
                    ),
                    "bus:ownUser" => array(
                        array( "value" => $_SESSION['user_uri'], 
                            "type" => "uri")
                    )
                ) 
            );
            // split sParentCategory into array Categories
            $str = chop($category);
            $sCategories = explode(';', $str);
            //                print($str);
            $aCategories = array();
            foreach($sCategories as $sCategory)
            {
                $aTemp = array( "value" => $sCategory ,"type" => "uri");
                array_push($aCategories , $aTemp);
            }
            $data[$uri]['bus:childCategoryOf'] = $aCategories;
            $oDatabase ->updateResources($aNameSpace,$data,$product_id,$sType);
        }

        public function updateFlowProduct()
        {
            // uri_user,property follow, function(delete,add),value uri follow
            core::checkSession();
            $oDatabase = new database();
            $uri = URL::getLink("profile/id/".$_SESSION['username']);
            if($this->checkUpdate($uri,$_POST['property'],$_POST['func'],$_POST['value']))
            {
                $product = chop($_POST['product']);
                $user = chop($_POST['flow_user']);
                // Add namespace for rdf file
                $ns = array(
                    'rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
                    'foaf' => 'http://xmlns.com/foaf/0.1/',
                    'bus' => URL::getLink('id/bussiness#'),
                );
                $conf = array('ns' => $ns);
                $ser = ARC2::getRDFXMLSerializer($conf);
                $graph = new Graphite();
                $graph->ns('bus',URL::getLink('id/bussiness'));
                $graph->setDebug( true );
                $uriuser = URL::getLink("profile/id/".$_SESSION['username']);
                $graph->load($uriuser );
                $familyname = $graph->resource($uriuser)->get('foaf:familyName');
                $givenName = $graph->resource($uriuser)->get('foaf:givenName');
                $location = $graph->resource($uriuser)->get('bus:#location');
                $mbox = $graph->resource($uriuser)->get('foaf:mbox');
                $hasSetting = $graph->resource($uriuser)->get('bus:#hasSetting');
                $imagePer = $graph->resource($uriuser)->get('bus:#image');
                $data = array(
                    $uri => array(
                        "rdf:type" => array( 
                            array( "value" => "http://xmlns.com/foaf/0.1/Person", 
                                "type" => "uri" ) 
                        ) ,
                        "foaf:familyName" => array(
                            array( "value" => $familyname, 
                                "type" => "literal")
                        ),
                        "foaf:givenName" => array(
                            array( "value" => $givenName, 
                                "type" => "literal")
                        ),
                        "foaf:mbox" => array(
                            array( "value" => $mbox, 
                                "type" => "literal")
                        ),
                        "bus:location" => array(
                            array( "value" => $location, 
                                "type" => "literal")
                        ),
                        "bus:image" => array(
                            array( "value" => $imagePer, 
                                "type" => "literal")
                        ),
                        "bus:hasSetting" => array(
                            array( "value" => $hasSetting, 
                                "type" => "uri")
                        ),
                    ) 
                );
                // split sParentCategory into array Categories
                if($product != '')
                {
                    $str = chop($product);
                    $sproduct = explode(';', $str);
                    //                print($str);
                    $aproduct = array();
                    foreach($sproduct as $sCategory)
                    {
                        $aTemp = array( "value" => $sCategory ,"type" => "uri");
                        array_push($aproduct , $aTemp);
                    }
                    $data[$uri]['bus:followProduct'] = $aproduct;
                }
                if($user != '')
                {
                    $str = chop($user);
                    $sUser = explode(';', $str);
                    $aUser = array();
                    foreach($sUser as $sCategory)
                    {
                        $aTemp = array( "value" => $sCategory ,"type" => "uri");
                        array_push($aUser , $aTemp);
                    }
                    $data[$uri]['bus:followUser'] = $aUser;
                }
                $oDatabase ->updateResources($ns,$data,$_SESSION['username'],'profile');
                echo $location;
            }
            else
            {
                echo 'Database not exits';
            }
        }

        public function checkUpdate($uri,$property,$function,$value)
        {
            $squeryfollow ='PREFIX foaf: <http://xmlns.com/foaf/0.1/>
            PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
            PREFIX dc: <http://purl.org/dc/elements/1.1/>
            PREFIX bus: <'.URL::getLink('id/bussiness#').'>

            SELECT * 
            WHERE
            {
            ?uri rdf:type foaf:Person.
            OPTIONAL{?uri bus:'.$property.' ?follow. } 
            FILTER(?uri = "'.$uri.'").
            }';
            $oDatabase = new database();
            $aResult = $oDatabase->loadQuery($squeryfollow);   
            $aResulProperty=$aResult['result']['rows'];
            $sresult ='';
            if(count($aResulProperty))
            {
                if($function == 'ADD')// add Property
                {
                    foreach($aResulProperty as $item)
                    {
                        if(isset($item['follow']))
                        {
                            if($item['follow'] == $value)
                                return false;
                        }
                        else
                        {
                            return true;
                        }
                    }
                    return true;
                }
                else// Delete Property
                {
                    foreach($aResulProperty as $item)
                    {
                        if($item['follow'] == $value)
                            return true;
                    }
                    return false;
                }

            }
            else
            {
                if($function == 'ADD')// add Property
                    return true;
                else
                    return false;
            }
        } 

        public function addHotProduct()
        {
            core::checkSession();
            if(isset($_POST['productUri']))
            {
                if(database::isAdmin())
                {
                    $uri = URL::getLink('id/hotProduct');
                }
                else
                {
                    $uri = URL::getLink('id/'.$_SESSION['user_uri'].'_hotProduct');
                }
                $oDatabase = new database();
                $oDatabase->addProperity($uri,'bus:hasProduct',$_POST['productUri']);
                echo "OK";
            }
        }

        public function loadImageOfProduct()
        {
            $aParams = array(
                'uri' => $_POST['productUri'],
            );
            includeBlock('block/imageBlock',$aParams);
        }

        public function addImage()
        {
            if(isset($_POST['productUri']))
            {
                $uri = $_POST['productUri'];
                $oDatabase = new database();
                $oDatabase->addProperity($uri,'bus:image',URL::getLink('upload/'.$_POST['image']));
            }
        }

        public function setDefaultImage()
        {
            if(isset($_POST['productUri']))
            {
                $uri = $_POST['productUri'];
                $oDatabase = new database();
                $result = $oDatabase->setProperity($uri,'bus:defaultImage',URL::getLink('upload/'.$_POST['image']));
                if($result)
                {
                    echo 'OK';
                }
                else
                {
                    echo 'FAIL';
                }
            }
        }

        public function setHotImage()
        {
            if(isset($_POST['productUri']))
            {
                $uri = $_POST['productUri'];
                $oDatabase = new database();
                $oDatabase->setProperity($uri,'bus:hotImage',$_POST['image']);
            }
        }

        public function setHighLightImage()
        {
            if(isset($_POST['productUri']))
            {
                $uri = $_POST['productUri'];
                $oDatabase = new database();
                $oDatabase->setProperity($uri,'bus:hightLightImage',$_POST['image']);
            }
        }

        public function hightLightProduct()
        {
            if(isset($_POST['productUri']))
            {
                $uri = $_POST['productUri'];
                $oDatabase = new database();
                $oDatabase->setProperity($uri,'bus:isHightLight','true');
            }
        }

        public function removeHightLightProduct()
        {
            if(isset($_POST['productUri']))
            {
                $uri = $_POST['productUri'];
                $oDatabase = new database();
                $oDatabase->removeProperity($uri,'bus:isHightLight');
            }
        }

        public function addLikeUser()
        {
            core::checkSession();
            if(!isset($_SESSION['user_uri']))
            {
                echo 'FALSE';
                return;
            }
            if(isset($_POST['uri']))
            {
                $oDatabase = new database();
                $oDatabase->addProperity($_POST['uri'],'bus:userLike',$_SESSION['user_uri']);
            }
        }

        public function dislikeProduct()
        {
            core::checkSession();
            if(!isset($_SESSION['user_uri']))
            {
                echo 'FALSE';
                return;
            }
            if(isset($_POST['uri']))
            {
                $oDatabase = new database();
                $oDatabase->removeProperity($_POST['uri'],'bus:userLike',$_SESSION['user_uri']);
            }
        }

        public function removeImage()
        {
            core::checkSession();
            if(!isset($_SESSION['user_uri']))
            {
                echo 'FALSE';
                return;
            }
            if(isset($_POST['uri']))
            {
                $oDatabase = new database();
                $oDatabase->removeProperity($_POST['uri'],'bus:image',$_POST['image']);
            }
        }

        public function deleteProduct()
        {
            core::checkSession();
            if(database::isUser())
            {
                if(isset($_POST['productUri']))
                {
                    $uri = $_POST['productUri'];
                    $graph = new Graphite();
                    $graph->ns('bus',URL::getLink('id/bussiness#'));
                    $graph->load($uri );
                    $ownUser = $graph->resource($uri)->getString('bus:ownUser');
                    if($ownUser == $_SESSION['user_uri'] || database::isAdmin())
                    {
                        $oDatabase = new database();
                        $oDatabase->deleteResources($uri);
                    }
                    else
                    {
                        echo 'FALSE';
                        return;
                    }
                }
                else
                {
                    echo 'FALSE';
                    return;
                }
            }
            else
            {
                echo 'FALSE';
                return;
            }
        }
        
        public function quickViewProduct()
        {
            if(isset($_POST['uri']))
            {
                $aParams = array(
                    'uri' => $_POST['uri'],
                );
                includeBlock('block/quickViewBlock', $aParams);
            }
        }
    }
?>
